--
-- DailyController.lua
-- Created by IntelliJ IDEA.
-- User: yao.chen
-- Date: 2018/12/27
--

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

local DailyView = import("..views.DailyView")
local DailyRewardView = require("app.task.views.DailyRewardView")
local BlessView = require("app.worldMap.views.BlessView")
local BlessRewardView = require("app.worldMap.views.BlessRewardView")

-- 活动funcId
local TAB_INDEX_TO_FUNC_ID = {
    [1] = Constant.FUNC_TYPE_DAILY_TASK,
    [2] = Constant.FUNC_TYPE_DAILY_RARE,
    [3] = Constant.FUNC_TYPE_DAILY_WISH_WORLD
}

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._model = app:getInst("DailyModel")
    self._worldMapModel = app:getInst("WorldMapModel")
    self._walletHandler = UD:onChanged("wallet", handler(self, self.updatePlayer))
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)
    UD:unChanged("wallet", self._walletHandler)
end

function ClassRef:onEvent(eventName, data)
    if eventName == "onMapChanged" then
        if data then
            self._worldMapModel:reqWorldBlessInfo()
        end
    elseif eventName == "onDailyUpdate" then
        -- 跨天，清除数据和界面，重新打开会更新数据
        self._worldMapModel:clearBlessRewards()
        self:closeView()
        UIHandler:removePopupUiByKey(BlessView:getViewName())
        UIHandler:removePopupUiByKey(BlessRewardView:getViewName())
    end
end

function ClassRef:listEvent()
    return {
        "onMapChanged",
        "onDailyUpdate",
    }
end

function ClassRef:openView(data)
    if cc.isDead(self._view) then
        self._view = DailyView.new(app.mvc.VIEWTYPE_BLUR)
        self._view:onCloseView(handler(self, self.closeView))
        self._view:onClearView(handler(self, self.clearView))
        self._view:onOperate(handler(self, self.onOperate))
        self._view:onSwitchPanel(handler(self, self.onSwitchPanel))
    end

    self:addChild(self._view, data)
    self._view:setNodeVisible()
    -- 默认选中开启的第一个页签活动， 如果有指定的页签，判断该页签活动是否开启
    local curIndex
    for i, v in ipairs(TAB_INDEX_TO_FUNC_ID) do
        if UIHandler:isFunctionOpen(v) then
            curIndex = i
            break
        end
    end
    if data and UIHandler:isFunctionOpen(TAB_INDEX_TO_FUNC_ID[data]) then
        curIndex = data
    end

    if not curIndex then return end

    self._view:show(curIndex or 1)

    -- 把经验条 提到 popUI的上一层
    app:sendMsg("PlayerController", "showExpBar", SceneZOrder.popupUIZOrder + 1)

    self:removeTaskListener()
    self._taskHandlers = {}
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("GET_DAILY_QUESTINFO_OK", function(event)
        if cc.isAlive(self._view) then
            self._view:updateTaskProgress("daily")
        end
    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("REFRESH_TASK_OK", function(event) -- 支线和每日任务领奖成功返回
        if event.taskType == "daily" then
            if cc.isAlive(self._view) then
                self._view:onGetDailyTaskAward(event.taskId)
            end
        end
    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("REFRESH_DAILY_TASK_OK", function(event) -- 每日任务 刷新
        local refreshIndex = self._model:getRefreshIndex()
        self._view:playDailyRefreshAni(refreshIndex)
        self._model:setRefreshIndex(nil)
    end)
end

-- mapInfo = MapInfo
function ClassRef:openBlessView(mapInfo)
    if not self:isViewAlive() then return end

    local view = BlessView.new(app.mvc.VIEWTYPE_MODAL_BG)
    view:onCloseView(function(sender)
        sender:removeFromParent()
    end)
    view:onOperate(function(op, data)
        if op == "openBlessReward" then
            self:openBlessRewardView(data)
        end
    end)

    local blessTimes = self._worldMapModel:getBlessTimes()
    view:refreshBlessTimes(blessTimes)
    view:refresh(mapInfo)
    view:setName(view:getViewName())
    self._view:addChild(view)
    view:show()
end

-- zoneInfo = ZoneInfo
function ClassRef:openBlessRewardView(zoneInfo)
    if not self:isViewAlive() then return end

    local view = BlessRewardView.new(app.mvc.VIEWTYPE_MODAL_BG)
    view:onCloseView(function(sender)
        sender:removeFromParent()
    end)
    view:onOperate(function(op, data)
        if op == "reqBless" then
            self._worldMapModel:reqBlessZone(data.id)
        end
    end)

    local blessTimes = self._worldMapModel:getBlessTimes()
    view:refreshBlessTimes(blessTimes)
    local blessRewards = self._worldMapModel:getBlessRewards(zoneInfo.id)
    view:refreshRewards(blessRewards)
    view:refresh(zoneInfo)
    view:setName(view:getViewName())
    self._view:addChild(view)
    view:show()
end

function ClassRef:onBlessZone(zoneInfo, blessTimes)
    UD.redPoint:checkStateByKey(Constant.FUNC_TYPE_DAILY_WISH_WORLD)
    if not self:isViewAlive() then return end

    self._view:refreshBlessTimes(blessTimes)
    self._view:refreshTabBtnRedPoints(Constant.FUNC_TYPE_DAILY_WISH_WORLD)
    -- BlessView ui update
    local view = self._view:getChildByName(BlessView:getViewName())
    if view then
        view:refreshBlessTimes(blessTimes)
        view:updateZone(zoneInfo)
    end
end

function ClassRef:closeView(data)
    if self._view then
        self:removeChild(self._view, data)
        -- 更新 每日任务 按钮红点
        if TaskManager:checkHasRewardByTaskType(2) then
            UD.redPoint:setStateByKey(Constant.FUNC_TYPE_DAILY_TASK, true)
        else
            UD.redPoint:setStateByKey(Constant.FUNC_TYPE_DAILY_TASK, false)
        end

        self:clearView()
    end
end

function ClassRef:clearView()
    self:removeTaskListener()

    if self._view then
        self._view = nil
    end

    app:sendMsg( "PlayerController", "showExpBar" )
end

function ClassRef:removeTaskListener()
    if self._taskHandlers then
        for _, v in ipairs(self._taskHandlers) do
            TaskManager:removeEventListener(v)
        end
        self._taskHandlers = {}
    end
end

-- 显示每日任务奖励预览UI
function ClassRef:showDailyReward(data, isPrivilegeBox)
    local view = DailyRewardView.new()
    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
    end)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
--    view:showData(isLock, boxIndex, questType, itemLists)
    view:showData(data, isPrivilegeBox)
end

function ClassRef:closeSelf()
    UIHandler:handleMessage({id = Constant.FUNC_TYPE_DAILY_TASK, mode = "close"})
end

function ClassRef:updateNewTasks(tasks)
    if not tasks then return end

    -- 更新主界面任务红点
    if TaskManager:checkHasRewardByTaskType(2) then
        UD.redPoint:setStateByKey(Constant.FUNC_TYPE_DAILY_TASK, true)
    end

    if not cc.isDead(self._view) then
        self._view:updateNewTasks(tasks)
    end
end

function ClassRef:updatePrivilegeInfo(msg)
    if not self._view then return end
    self._view:updatePrivilegeInfo(msg)
end

function ClassRef:refreshPrivilegeBox(msg)
    if not self._view then return end
    self._view:refreshPrivilegeBox(msg)
end

function ClassRef:onSwitchPanel(idx)
    self._curIdx = idx
    if idx == 1 then
        self:onOperate("GET_DAILY_INFO")
        self:onOperate("getGetSuperPrivilegeInfo")
    elseif idx == 2 then
    elseif idx == 3 then
        self:onOperate("reqWorldBlessInfo")
    end
end

function ClassRef:onOperate(op, data)
--    print("DailyController:onOperate op = " .. op)
    if op == "OPEN_REWARD" then
        local itemList = self._model:getDailyTaskRewards(data.needProgress, data.nowProgress)
        local lvData = data
        lvData.itemList = itemList
        self:showDailyReward(lvData, false)
    elseif op == "GET_TASK_REWARD" then
        TaskManager:C2S_GetTaskRewardRequest(data.taskType, data.taskId)
    elseif op == "GET_DAILY_INFO" then
        TaskManager:C2S_GetDailyTaskInfoRequest()
    elseif op == "refreshDailyTask" then
        self._model:setRefreshIndex(data:getPos())
        TaskManager:C2S_RefreshDailyTaskRequest(data:getId())
    elseif op == "TASK_AUTO_WAY" then
        EM:notify("onTrackingWay",{trackNpcId = data.findNpcId, trackTaskId = data.trackTaskId, isTracking = true, findCall = function(isFinding)
            if isFinding then
                self:closeSelf()
            end
        end})
    --祝福世界
    elseif op == "openBless" then
        self:openBlessView(data)
    elseif op == "reqWorldBlessInfo" then
        self._worldMapModel:reqWorldBlessInfo(function()
            if cc.isDead(self._view) then return end
            local mapInfos = self._worldMapModel:getMapInfos()
            local blessTimes = self._worldMapModel:getBlessTimes()
            self._view:refresh(mapInfos)
            self._view:refreshBlessTimes(blessTimes)
        end)
    elseif op == "gotoFeature" then
        --宝箱界面点击前往按钮跳转
        if data then
            UIHandler:handleMessage({id = data, mode = "open"})
        end
    elseif op == "OPEN_PRIVILEGE_BOX" then
        self:showDailyReward(data, true)
    else
        if self._model[op] ~= nil then
            if data and type(data) == "table" then
                return self._model[op](self._model, data[1], data[2]) -- 如果有多个参数，就直接在后面添加
            else
                return self._model[op](self._model, data)
            end
        end
    end
end

------------------------------update------------------------
function ClassRef:updatePlayer(name, old, new)
    if not self:isViewAlive() then 
        if name == "dungeonLuckBox" or name == "eventLuckBox" or name == "arenaLuckBox" then
            RedPointHandler.onRareChange()
        end
		return 
	end
    if name == "dungeonLuckBox" or name == "eventLuckBox" or name == "arenaLuckBox" then
        self:onRareChange()
	end
end

function ClassRef:onRareChange()
    if not self:isViewAlive() then 
		RedPointHandler.onRareChange()
		return 
	end
	RedPointHandler.onRareChange()
	if self._curIdx == 2 then
        self._view:refresh()
        self._view:refreshRareRedPoint()
	end
end

return ClassRef
